﻿using iTextSharp.text.pdf;
using System.IO;

namespace Think9.Services.Com
{
    public class PdfService
    {
        public void MergeExport(string idsStr)
        {
        }

        public static void MergePDF(string sourcePath, string targetPath, string newFileName)
        {
            //需要合并的pdf集合
            string[] fileList = Directory.GetFiles(sourcePath, "*.pdf", SearchOption.AllDirectories);
            //合并到的总PDF
            string outMergeFile = targetPath + "\\" + newFileName;
            iTextSharp.text.pdf.PdfReader reader;
            iTextSharp.text.Document document = new iTextSharp.text.Document();
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outMergeFile, FileMode.Create));
            document.Open();
            PdfContentByte cb = writer.DirectContent;
            PdfImportedPage newPage;
            for (int i = 0; i < fileList.Length; i++)
            {
                reader = new PdfReader(fileList[i]);
                int iPageNum = reader.NumberOfPages;
                for (int j = 1; j <= iPageNum; j++)
                {
                    document.NewPage();
                    newPage = writer.GetImportedPage(reader, j);
                    cb.AddTemplate(newPage, 0, 0);
                }
            }
            document.Close();
        }
    }
}